package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.mapper.ClubActivityMapper;
import com.quanyan.common.utils.Limit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yue.yuan on 2016/8/26.
 */
@Component
public class ActivityStatusUpdateJob implements JobRunner {

    private static Logger logger = Logger.getLogger(ActivityStatusUpdateJob.class);

    @Autowired
    private ClubActivityMapper clubActivityMapper;

    @Autowired
    private ActivityOpenService activityOpenService;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        float targetStatus = ClubConstants.CLUB_ACTIVITY_STATUS_END;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isEnd", 1L);
        updateStatus(targetStatus, map);
        targetStatus = ClubConstants.CLUB_ACTIVITY_STATUS_START;
        map.clear();
        map.put("isStart", 1L);
        updateStatus(targetStatus, map);
        return new Result(Action.EXECUTE_SUCCESS);
    }

    private void updateStatus(float targetStatus, Map<String, Object> map)
    {
        //查找有多少标记为未结束的
        int total = clubActivityMapper.countActivityIdByStatus(targetStatus);
        Integer pageSize = 20;
        int successCount = 0;
        int all = 0;
        for (int i = 0; i < Math.ceil((double)total/pageSize); i++) {
            int pageNum = i + 1;
            Limit limit = Limit.buildLimit(pageNum, pageSize);
            List<Integer> idList = clubActivityMapper.selectActivityIdByStatus(targetStatus, limit.getStart(), limit.getSize());
            //从这些标记未结束的活动中找出实际结束或实际进行中的活动
            List<Integer> endIds = activityOpenService.queryActivityIdsByCondition(idList, map);
            //将这些实际结束或进行中的活动标记为已结束
            if(null != endIds && endIds.size() > 0)
            {
                logger.warn("开始更新活动状态:" + "目标状态" + targetStatus);
                successCount += clubActivityMapper.updateStatusByActivityId(targetStatus, endIds);
                all += endIds.size();
            }
        }
        logger.warn("更新活动状态完成，有效数:" + successCount + "总数:" + total);
    }

}
